import React from 'react';
import { Group } from '@vx/group';
import { Tree } from '@vx/hierarchy';
import { LinearGradient } from '@vx/gradient';
import { hierarchy } from 'd3-hierarchy';
import Links from './Links';
import Nodes from './Nodes';

export default class TreeSvg extends React.Component {
  state = {
    layout: 'cartesian',
    orientation: 'horizontal',
    linkType: 'diagonal',
    stepPercent: 0.5,
  };

  render() {
    const {
      data,
      width,
      height,
      nodeClick,
      children,
      nodeKey,
      margin = {
        top: 60,
        left: 30,
        right: 30,
        bottom: 30,
      },
      ...restProps
    } = this.props;
    const { layout, orientation, linkType, stepPercent } = this.state;

    if (width < 10) return null;

    const innerWidth = width - margin.left - margin.right;
    const innerHeight = height - margin.top - margin.bottom;

    let origin = { x: 0, y: 0 };
    let sizeWidth;
    let sizeHeight;

    if (orientation === 'vertical') {
      sizeWidth = innerWidth;
      sizeHeight = innerHeight;
    } else {
      sizeWidth = innerHeight;
      sizeHeight = innerWidth;
    }
    const roots = data.map(item => (children ? hierarchy(item, children) : hierarchy(item)));

    let gutter = sizeWidth / roots.length / 4;
    return (
      <>
        {roots.map((root, index) => {
          return (
            <React.Fragment key={index}>
              <Tree
                root={root}
                size={[200, sizeHeight / 2]}
                separation={(a, b) => (a.parent == b.parent ? 1 : 0.5) / a.depth}
              >
                {data => {
                  return (
                    <Group top={200 * index} left={100}>
                      <Links
                        links={data.links()}
                        linkType={linkType}
                        layout={layout}
                        orientation={orientation}
                        stepPercent={stepPercent}
                      />

                      <Nodes
                        nodes={data.descendants()}
                        rootKey={index + 1}
                        nodeKey={nodeKey || 'name'}
                        layout={layout}
                        orientation={orientation}
                        onNodeClick={nodeClick}
                        {...restProps}
                      />
                    </Group>
                  );
                }}
              </Tree>
            </React.Fragment>
          );
        })}
      </>
    );
  }
}
